let iconEle = document.querySelector('.icon')
let usernameEle = document.querySelector('.username')
let inputEle = document.querySelector('.chatInput')
let middle = document.querySelector('.middle')


//*键盘回车时发送把content的值送到后端
inputEle.onkeyup = function(e) {
  if(e.keyCode == 13) {
    sendMessage()
  }
}
function sendMessage (e) {
  if (inputEle.value && inputEle.value !== '') {
    $.ajax({
      type: 'get',
      url: 'http://localhost:30001/user/sendMessage',
      data: { content: inputEle.value },
      success: function (result) {
        if (result.status === 'success') {
          
                        //*将返回到元素直接渲染到页面上指定的位置
          middle.innerHTML += '<div class="line">' + result.username +
                            '<img src=' + result.avatar + '>' +
                            '<div class="container">' + result.content + '</div>'
                             + '<div class="time">' + moment(result.time).format('YYYY年MM月DD日  hh:mm: s') + '</div>' + '</div>'
          scrollToBottom(middle)
        }
      }
    })
            //*设置回车之后将内容清空
    inputEle.value = ''
  }
}

    
//*初始化登录成功后将数据库的聊天内容渲染到聊天界面
function init(){
  $.ajax({
    type: 'get',
    url: 'http://localhost:30001/user/getContent',
    data:{},
    success:function (result) {
    //   if(result.status === 'success'){

      let html = ''
      result.forEach(element => {
        html += '<div class="line">' + element.username +
            '<img src=' + element.avatar + '>' +
            '<div class="container">' + element.content + '</div>' + 
            '<div class="time">' + moment(element.time).format('YYYY年MM月DD日  hh时mm分 s秒') + '</div>' + '</div>'
      })
      middle.innerHTML = html
      scrollToBottom(middle)
    }
    // }
  })
}
init()

//*设置滚轮将聊天室的内容自动定位到最新
function scrollToBottom(ele){

  if(ele){
    ele.scrollTop = ele.scrollHeight 
  }
}
 
// setInterval(function (){
//   init()
// },1000)